<template>
  <div>
    <el-dialog
      :visible="isShowDialog"
      :title="`${formData.id?'编辑':'添加'}分类`"
      :destroy-on-close="closeDialog"
      @close="btnClose"
    >
      <el-form ref="formData" :model="formData" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="formData.desc" type="textarea" />
        </el-form-item>
        <el-form-item label="封面">
          <ImageUpload ref="formDataPhoto" />
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="end">
        <el-col :span="6">
          <el-button type="primary" size="small" @click="btnOk">确定</el-button>
          <el-button size="small" @click="btnClose">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { addCategory, editCategory, updateCategory } from '@/api/category'
export default {
  props: {
    isShowDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        desc: ''
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ]
      },
      imgList: [],
      closeDialog: false
    }
  },
  methods: {
    async btnOk() {
      const fileList = this.$refs.formDataPhoto.fileList
      await this.$refs.formData.validate()
      if (this.formData.id) {
        await updateCategory({ ...this.formData, image: fileList[0]?.url })
        this.$message.success('编辑成功')
      } else {
        await addCategory({ ...this.formData, image: fileList[0]?.url })
        this.$message.success('添加成功')
      }
      this.$emit('update:isShowDialog', false)
      this.$emit('addCategory')
    },
    async btnClose() {
      this.formData = {
        title: '',
        desc: ''
      }
      this.closeDialog = true
      await this.$refs.formData.resetFields()
      this.$emit('update:isShowDialog', false)
    },
    async editCategory(id) {
      this.formData = await editCategory(id)
      // console.log(this.formData)
      // console.log(this.$refs.formDataPhoto)
      if (this.formData.image) {
        this.$refs.formDataPhoto.fileList = [
          { url: this.formData.image }
        ]
      }
    }
  }
}
</script>

<style>

</style>
